#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , m_db(QSqlDatabase::addDatabase("QODBC"))
{
    ui->setupUi(this);

    connect(ui->pushButton_register, &QPushButton::clicked, this, &Widget::registerbtn_clicked);

    // 初始化数据库
    init_db();


}

Widget::~Widget()
{
    delete ui;
}

void Widget::init_db(){
    m_db.setHostName("127.0.0.1");
    m_db.setPort(3306);
    m_db.setUserName("root");
    m_db.setPassword("wb412412");
    m_db.setDatabaseName("MySQL57");

    if(m_db.open()){
        qDebug() << "connect database success.";
        return;
    }

    qDebug() << "connect database fail";
    exit(1);
}

void Widget::registerbtn_clicked(){
    QString strname = ui->lineEdit_userName->text();
    QString strpwd = ui->lineEdit_passWord->text();

    QString strsql = QString("insert into test_user(name, password) values('%1', '%2');").arg(strname).arg(strpwd);

    qDebug() << strsql;

    QSqlQuery query;

    if(query.exec(strsql)){
        qDebug() << "send sql success" ;
        return;
    }

    qDebug() << "send sql fail" << query.lastError().text();
    return;

}
